import copy
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from MedicineReminder.models import Medicine
from SecureHelperServer.settings import formatResponseData
from utils.conf import verifyID, Response
from utils.custom import MyJWTAuthentication


class RemoveMedicineView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        删除药品
        """
        data = copy.deepcopy(formatResponseData)
        try:
            medicineId = request.data.get("medicineId")

            if not medicineId:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            if not verifyID(medicineId):
                return Response(data=data, responseMsg="药品不存在",
                                loggerMsg=f"删除药品：medicineId={medicineId}不是一个有效的id", isError=True)

            medicine = Medicine.objects.filter(id=medicineId, user=request.user).first()

            if not medicine:
                return Response(data=data, responseMsg="药品不存在",
                                loggerMsg=f"删除药品：未找到medicineId={medicineId}对应的药品", isError=True)
            # 删除药品
            medicine.delete()

            return Response(data=data, responseMsg="删除成功",
                            loggerMsg=f"删除药品: 成功，uid={request.user.uid}，medicineId={medicineId}")

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
